<template>
  <div class="review-list-container">
    <el-card class="page-container">
      <template #header>
        <div class="header">
          <span>我的酒店评价</span>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div v-else-if="error" class="error-container">
        <el-empty :description="errorMessage">
          <template #extra>
            <el-button type="primary" @click="initData">重试</el-button>
          </template>
        </el-empty>
      </div>
      
      <div v-else>
        <el-table v-if="tableData.length > 0" :data="tableData" stripe style="width: 100%">
          <el-table-column prop="userId" label="用户ID"/>
          <el-table-column prop="content" label="评论内容" show-overflow-tooltip/>
          <el-table-column label="评分">
            <template #default="{ row }">
              <el-rate v-model="row.rating" disabled show-score />
            </template>
          </el-table-column>
          <el-table-column label="评论时间">
            <template #default="{ row }">
              {{ formatDate(row.reviewTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewReviewDetail(row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <el-empty v-else description="暂无评价数据"></el-empty>
        
        <div v-if="tableData.length > 0" class="pagination-box">
          <el-pagination background layout="total, prev, pager, next"
                         v-model:current-page="pageIndex"
                         :page-size="pageSize"
                         @current-change="handleCurrentChange"
                         :total="total"/>
        </div>
      </div>
      
      <!-- 评价详情对话框 -->
      <el-dialog v-model="reviewDetailVisible" title="评价详情" width="50%">
        <div v-if="currentReview" class="review-detail">
          <div class="review-header">
            <div class="review-user">用户ID: {{ currentReview.userId }}</div>
            <div class="review-time">{{ formatDate(currentReview.reviewTime) }}</div>
          </div>
          <div class="review-rating">
            <span>评分: </span>
            <el-rate v-model="currentReview.rating" disabled show-score />
          </div>
          <el-divider />
          <div class="review-content">
            <h3>评价内容:</h3>
            <p>{{ currentReview.content }}</p>
          </div>
          
          <el-divider />
          <div class="reply-section">
            <h3>评论回复:</h3>
            <div v-if="loadingReplies" class="loading">
              <el-skeleton :rows="3" animated />
            </div>
            <div v-else-if="replies.length === 0" class="no-replies">
              暂无回复
            </div>
            <div v-else class="reply-list">
              <div v-for="(reply, index) in replies" :key="index" class="reply-item">
                <div class="reply-header">
                  <span class="reply-user">{{ reply.userId }}</span>
                  <span class="reply-time">{{ formatDate(reply.replyTime) }}</span>
                </div>
                <div class="reply-content">{{ reply.content }}</div>
              </div>
            </div>
            
            <div class="add-reply">
              <h3>添加回复</h3>
              <el-input
                v-model="replyContent"
                type="textarea"
                :rows="3"
                placeholder="请输入回复内容"
              />
              <div class="reply-actions">
                <el-button type="primary" @click="submitReply" :loading="submitting">提交回复</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { getReviewList, getReviewsByHotel, getReviewReplies, addReviewReply, getHotelReviewNotifications, markReviewNotificationAsRead } from '@/api/review'
import { ElMessage } from 'element-plus'
import { getHotelByUserId } from '@/api/hotel'
import { useUserInfoStore } from '@/stores/userInfo'

const tableData = ref([])
const loading = ref(true)
const error = ref(false)
const errorMessage = ref('获取评价列表失败')
const userInfoStore = useUserInfoStore()
const hotelName = ref('')
const pageIndex = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 评价详情相关
const reviewDetailVisible = ref(false)
const currentReview = ref(null)
const loadingReplies = ref(false)
const replies = ref([])
const replyContent = ref('')
const submitting = ref(false)

// 格式化日期
const formatDate = (dateStr: string | null) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString()
}

const initData = async () => {
  if (!userInfoStore.userInfo || !userInfoStore.isHotelOwner()) {
    errorMessage.value = '您没有访问此页面的权限'
    error.value = true
    loading.value = false
    return
  }
  
  loading.value = true
  error.value = false
  
  try {
    // 先获取用户关联的酒店
    const userId = userInfoStore.userInfo.user.userId
    const hotelRes = await getHotelByUserId(userId)
    const hotelResult = hotelRes.data as any
    
    if (hotelResult && hotelResult.code === 200 && hotelResult.data) {
      hotelName.value = hotelResult.data.hotelName
      
      // 使用getReviewsByHotel函数直接获取酒店评价
      const res = await getReviewsByHotel(hotelName.value)
      const result = res.data as any
      
      console.log('获取酒店评价响应:', result)
      
      // 检查返回的数据结构
      if (Array.isArray(result)) {
        // 直接返回数组格式
        tableData.value = result
        total.value = result.length
      } else if (result && (result.code === 200 || result.code === 0)) {
        // 标准响应格式：{code: 200/0, data: [...], msg: '...'}
        tableData.value = Array.isArray(result.data) ? result.data : []
        total.value = tableData.value.length
      } else {
        error.value = true
        errorMessage.value = result?.msg || '获取评价列表失败'
      }
    } else {
      error.value = true
      errorMessage.value = hotelResult?.msg || '获取酒店信息失败'
    }
  } catch (err) {
    console.error('获取评价列表错误:', err)
    error.value = true
    errorMessage.value = '网络错误，获取评价列表失败'
  } finally {
    loading.value = false
  }
}

const handleCurrentChange = (index: number) => {
  pageIndex.value = index
  // 这里我们在前端进行分页，因为已经筛选了当前酒店的评价
  // 实际项目中应该由后端提供酒店评价筛选API
}

const viewReviewDetail = (row) => {
  console.log('酒店评论详情对象：', row)
  console.log('评论对象字段：', Object.keys(row))
  
  // 确保row对象可以被正确复制
  try {
    // 创建一个新对象，确保reviewId字段存在
    const reviewObj = {
      ...row,
      // 如果原对象没有reviewId字段但有id字段，添加reviewId
      reviewId: row.reviewId || row.id || null
    }
    
    currentReview.value = reviewObj
    console.log('处理后的评论对象:', currentReview.value)
  } catch (error) {
    console.error('处理评论对象时出错:', error)
  currentReview.value = row
  }
  
  reviewDetailVisible.value = true
  replyContent.value = ''
  
  // 检查可能的ID字段
  const possibleIdField = row.id || row.reviewId || row.review_id || row.commentId || null
  console.log('找到的可能ID字段：', possibleIdField)
  
  if (!possibleIdField) {
    console.error('无法确定评论ID，评论对象：', row)
    ElMessage.warning('无法获取评论ID，无法加载回复')
    replies.value = []
    return
  }
  
  loadReplies(possibleIdField)
}

// 加载评论回复
const loadReplies = (reviewId) => {
  if (!reviewId) {
    ElMessage.warning('评论ID不存在，无法加载回复')
    replies.value = []
    return
  }
  
  // 确保reviewId为数字类型
  const numericReviewId = Number(reviewId)
  console.log('加载评论回复，处理后的评论ID:', numericReviewId, '类型:', typeof numericReviewId)
  
  if (isNaN(numericReviewId)) {
    console.error('评论ID无法转换为数字:', reviewId)
    ElMessage.error('评论ID格式错误')
    replies.value = []
    return
  }
  
  loadingReplies.value = true
  getReviewReplies(numericReviewId)
    .then(res => {
      console.log('获取评论回复响应结果:', res)
      
      // 处理直接返回数组的情况
      if (Array.isArray(res)) {
        console.log('响应直接是数组:', res)
        replies.value = res
        return
      }
      
      // 处理返回对象中data为数组的情况
      const result = res.data as any
      console.log('响应数据:', result)
      
      // 直接返回数组的情况（result本身就是数组）
      if (Array.isArray(result)) {
        console.log('响应数据是数组:', result)
        replies.value = result
        return
      }
      
      // 标准响应结构 {code:200, data:[...]}
      if (result && result.code === 200) {
        if (Array.isArray(result.data)) {
          replies.value = result.data
          console.log('解析后的回复列表:', replies.value)
        } else if (result.data && Array.isArray(result.data.records)) {
          replies.value = result.data.records
          console.log('从records字段中获取回复列表:', replies.value)
        } else {
          console.warn('回复数据格式不是数组:', result.data)
          replies.value = []
        }
      } else {
        console.error('获取评论回复失败，返回结果:', result)
        ElMessage.error(result?.msg || '获取评论回复失败')
        replies.value = []
      }
    })
    .catch(error => {
      console.error('获取评论回复失败:', error)
      ElMessage.error('网络错误，获取评论回复失败')
      replies.value = []
    })
    .finally(() => {
      loadingReplies.value = false
    })
}

// 提交回复
const submitReply = () => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('回复内容不能为空')
    return
  }
  
  if (!currentReview.value) {
    ElMessage.error('评论数据不存在，无法提交回复')
    return
  }
  
  console.log('当前评论对象:', currentReview.value)
  
  // 检查可能的ID字段
  const reviewId = currentReview.value.id || currentReview.value.reviewId || currentReview.value.review_id || currentReview.value.commentId
  
  if (!reviewId) {
    console.error('无法确定评论ID，评论对象：', currentReview.value)
    ElMessage.error('无法获取评论ID，无法提交回复')
    return
  }
  
  // 确保reviewId为数字类型
  const numericReviewId = Number(reviewId)
  console.log('提交回复的评论ID:', numericReviewId, '类型:', typeof numericReviewId)
  
  if (isNaN(numericReviewId)) {
    console.error('评论ID无法转换为数字:', reviewId)
    ElMessage.error('评论ID格式错误')
    return
  }
  
  const userId = userInfoStore.userInfo?.user?.userId
  if (!userId) {
    ElMessage.warning('请先登录')
    return
  }
  
  submitting.value = true
  
  const replyData = {
    reviewId: numericReviewId,
    userId: userId,
    content: replyContent.value
  }
  
  console.log('准备提交回复数据:', JSON.stringify(replyData))
  
  addReviewReply(replyData)
    .then(res => {
      console.log('添加回复响应结果:', res)
      
      // 处理直接返回布尔值的情况
      if (typeof res === 'boolean') {
        if (res) {
          ElMessage.success('回复提交成功')
          replyContent.value = ''
          loadReplies(numericReviewId)
        } else {
          ElMessage.error('回复提交失败')
        }
        return
      }
      
      const result = res.data as any
      if (result === true || result === 'success' || result === 1 || 
          (result && (result.code === 200 || result.code === 0))) {
        ElMessage.success('回复提交成功')
        replyContent.value = ''
        loadReplies(numericReviewId)
      } else {
        ElMessage.error(result?.msg || '回复提交失败')
      }
    })
    .catch(error => {
      console.error('提交回复失败:', error)
      ElMessage.error('网络错误，回复提交失败')
    })
    .finally(() => {
      submitting.value = false
    })
}

// 获取酒店评论通知
const fetchReviewNotifications = async () => {
  try {
    // 先获取用户关联的酒店
    const userId = userInfoStore.userInfo?.user?.userId
    if (!userId) {
      console.warn('用户未登录，无法获取酒店评论通知')
      return
    }
    
    // 获取酒店信息
    const hotelRes = await getHotelByUserId(userId)
    const hotelResult = hotelRes.data as any
    
    if (!(hotelResult && hotelResult.code === 200 && hotelResult.data && hotelResult.data.id)) {
      console.warn('无法获取酒店ID，无法获取评论通知')
      return
    }
    
    const hotelId = hotelResult.data.id
    const res = await getHotelReviewNotifications(hotelId)
    console.log('获取酒店评论通知响应:', res)
    
    // 处理通知数据
    if (res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
      // 如果有新的未读评论通知，提示用户
      const unreadNotifications = res.data.data.filter(notification => !notification.isRead)
      if (unreadNotifications.length > 0) {
        ElMessage({
          message: `您有 ${unreadNotifications.length} 条新的酒店评论`,
          type: 'info',
          duration: 5000,
          showClose: true
        })
        
        // 刷新评论列表
        initData()
        
        // 自动标记通知为已读
        unreadNotifications.forEach(notification => {
          markReviewNotificationAsRead(notification.id)
        })
      }
    }
  } catch (error) {
    console.error('获取酒店评论通知错误:', error)
  }
}

// 在组件挂载时获取评论列表和通知
onMounted(() => {
  initData()
  fetchReviewNotifications()
  
  // 定期检查新评论通知（每5分钟）
  const notificationInterval = setInterval(() => {
    if (userInfoStore.userInfo) {
      fetchReviewNotifications()
    }
  }, 300000) // 5分钟
  
  // 在组件卸载时清除定时器
  onBeforeUnmount(() => {
    clearInterval(notificationInterval)
  })
})
</script>
<style scoped>
.review-list-container {
  padding: 20px;
}

.page-container {
  min-height: 600px;
}
.header { 
  display: flex; 
  justify-content: space-between; 
  align-items: center; 
}
.loading-container, .error-container {
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.pagination-box { 
  padding-top: 16px; 
  display: flex; 
  justify-content: right; 
}
.review-detail {
  padding: 10px;
}
.review-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}
.review-user {
  font-weight: bold;
}
.review-time {
  color: #999;
}
.review-rating {
  margin-bottom: 15px;
}
.review-content {
  margin-bottom: 20px;
}
.review-content p {
  white-space: pre-wrap;
  line-height: 1.6;
}
.reply-section {
  margin-top: 20px;
}
.no-replies {
  text-align: center;
  padding: 20px;
  color: #909399;
  background: #f8f8f9;
  border-radius: 4px;
  margin-bottom: 20px;
}
.reply-list {
  margin-bottom: 20px;
}
.reply-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
}
.reply-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}
.reply-user {
  font-weight: bold;
}
.reply-time {
  color: #909399;
  font-size: 12px;
}
.reply-content {
  line-height: 1.6;
}
.add-reply {
  margin-top: 20px;
}
.reply-actions {
  margin-top: 10px;
  text-align: right;
}
</style> 